package com.heima.item.canal;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.heima.item.pojo.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

/**
 * <p>
 * ItemHandler
 * </p>
 *
 * @author flyduck
 * @since 2025/4/16
 */
@Slf4j
@Component
@CanalTable("tb_item")
public class ItemHandler implements EntryHandler<Item> {

    @Override
    public void insert(Item item) {
        log.info("监听到新增Item的消息了：{}",item);
        // 写数据到Caffeine缓存
        itemCache.put(item.getId(), item);
        // 写数据到redis缓存
        saveItem(item);
    }

    @Override
    public void update(Item before, Item after) {
        log.info("监听到更新Item的消息了：{}",after);
        // 写数据到Caffeine缓存
        itemCache.put(after.getId(), after);
        // 写数据到redis缓存
        saveItem(after);
    }

    @Override
    public void delete(Item item) {
        log.info("监听到删除Item的消息了：{}",item);
        // 从Caffeine缓存删除数据
        itemCache.invalidate(item.getId());
        // 从redis缓存删除数据
        deleteItemById(item.getId());
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Cache<Long,Item> itemCache;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private void saveItem(Item item) {
        try {
            String itemStr = MAPPER.writeValueAsString(item);
            stringRedisTemplate.opsForValue().set("item:id:" + item.getId(), itemStr);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    private void deleteItemById(Long id){
        stringRedisTemplate.delete("item:id:" + id);
    }
}
